import base64, pickle
from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, user, response):
    """购物车合并工具方法"""

    # 读取cookie中的购物车数据
    cart_str = request.COOKIES.get('cart')

    if not cart_str:
        # 如果没有cookie购物车数据不存在，就不需要合并，直接响应
        return response

    cart_str_bytes = cart_str.encode()
    cart_dict_bytes = base64.b64decode(cart_str_bytes)
    cookie_cart_dict = pickle.loads(cart_dict_bytes)

    # 读取redis中的购物车数据
    redis_conn = get_redis_connection('cart')

    redis_cart_dict = redis_conn.hgetall('cart_%s' % user.id)
    redis_cart_selected = redis_conn.smembers('selected_%s' % user.id)

    # 合并cookie到redis(核心代码)
    for sku_id, cookie_dict in cookie_cart_dict.items():
        # 将cookie_dict合并到redis_cart_dict
        redis_cart_dict[sku_id] = cookie_dict['count']

        # 将sku_id合并到redis_cart_selected
        if cookie_dict['selected']:
            redis_cart_selected.add(sku_id)

    # 需要将合并的数据同步到redis（核心代码）,也可以使用pipeline()实现
    redis_conn.hmset('cart_%s' % user.id, redis_cart_dict)
    redis_conn.sadd('selected_%s' % user.id, *redis_cart_selected)

    # 合并结束后，需要清空cookie中的购物车
    response.delete_cookie('cart')

    return response